package 回溯算法;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class subsets78 {

    /**
     * 所有的子集
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> subsets2(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        boolean[] vis = new boolean[nums.length];
        for (int i = 0; i <= nums.length; i++) {
            dfs(nums, 0, i, vis, list, lists);
        }
        return lists;

    }

    /**
     * 所有的子集
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        boolean[] vis = new boolean[nums.length];
        for (int i = 0; i <= nums.length; i++) {
            dfs(nums, 0, i, vis, list, lists);
        }
        return lists;

    }

    private void dfs(int[] nums, int index, int length, boolean[] vis, List<Integer> list, List<List<Integer>> lists) {
        if (list.size() == length) {
            ArrayList<Integer> tmp = new ArrayList<>();
            for (int i : list) {
                tmp.add(i);
            }
            Collections.sort(tmp);
            if (!lists.contains(tmp)) {
                // 这里需要排查在(0,1)(1,0)的两个元素
                lists.add(new ArrayList<>(tmp));
                return;
            } else {
                tmp.clear();
            }
        }
        for (int i = index; i < nums.length; i++) {
            if (!vis[i]) {
                vis[i] = true;
                list.add(nums[i]);
                dfs(nums, index + 1, length, vis, list, lists);
                list.remove(list.size() - 1);
                vis[i] = false;
            }
        }
    }

    @Test
    public void test() {
        List<List<Integer>> subsets = subsets(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 10, 0});
        for (List<Integer> list : subsets) {
            for (int i : list) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}